#include "Turret.h"

#include "InputHandler.h"
#include "Utility.h"
#include "GameGlobals.h"
#include "Resources.h"
#include "BaseMoveable.h"

LINKCLASSTONAME("ent_tankturret", Turret);

Turret::Turret(sf::RenderWindow *App) : BaseEntity(App)
{
	DrawOrder = 2;
	sprTurret.SetTexture(*Resources::Instance()->RequestImage("TankTurret"));
	sprTurret.SetOrigin(sprTurret.GetSize().x / 2, (sprTurret.GetSize().y / 2) + 3);
	LastFire = GameGlobals::Instance()->CurTime;
	LastMiniFire = LastFire;

	RegisterInput(std::string("shoot"), FireShell);
	RegisterInput(std::string("setenemy"), SetEnemy);
}

Turret::~Turret(void)
{
}

void Turret::FireShell(BaseEntity* ent)
{
	float delta = GameGlobals::Instance()->FrameTime;
	Turret* me = dynamic_cast<Turret*>(ent);
	if (me->LastFire + 1 < GameGlobals::Instance()->CurTime)
	{
		BaseEntity* b = EntityManager::Instance()->CreateEntity("ent_shell");
		BaseMoveable* bullet = dynamic_cast<BaseMoveable*>(b);
		float x,y;
		x = sin(Util::DegToRad(me->GetAngle()));
		y = cos(Util::DegToRad(me->GetAngle()));
		bullet->GetPhysicsObject()->SetVelocity(x * 700, y  * 700);
		BaseMoveable* own = dynamic_cast<BaseMoveable*>(me->mOwner);
		bullet->GetPhysicsObject()->AddVelocity(own->GetPhysicsObject()->GetVelocity());

		sf::Vector2f MuzzlePos;
		MuzzlePos.x = me->GetPos().x + (x * 70.f);
		MuzzlePos.y = me->GetPos().y + (y * 70.f);
		bullet->SetPos(MuzzlePos + Util::VecScale(own->GetPhysicsObject()->GetVelocity(), delta));
		bullet->SetOwner(own);
		me->LastFire = GameGlobals::Instance()->CurTime;
	}
}

void Turret::SetEnemy(BaseEntity* ent)
{
	Turret* me = dynamic_cast<Turret*>(ent);
	float delta = GameGlobals::Instance()->FrameTime;
	me->sprTurret.SetTexture(*Resources::Instance()->RequestImage("EnemyTurret"));
}

void Turret::Think()
{

}

void Turret::Draw()
{
	sprTurret.SetRotation(GetAngle());
	sprTurret.SetPosition(GetSFMLPos());
	pRender->Draw(sprTurret);
}
